define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mbti/scene/index' + location.search,
                    add_url: 'mbti/scene/add',
                    edit_url: 'mbti/scene/edit',
                    del_url: 'mbti/scene/del',
                    multi_url: 'mbti/scene/multi',
                    import_url: 'mbti/scene/import',
                    table: 'mbti_scene',
                }
            });

            Table.button = {
                edit: {
                    name: 'edit',
                    icon: 'fa fa-pencil',
                    title: __('Edit'),
                    extend: 'data-toggle="tooltip" data-container="body" data-area=["80%","80%"]',//调整弹窗尺寸
                    classname: 'btn btn-xs btn-success btn-editone'
                },
                del: {
                    name: 'del',
                    icon: 'fa fa-trash',
                    title: __('Del'),
                    extend: 'data-toggle="tooltip" data-container="body"',
                    classname: 'btn btn-xs btn-danger btn-delone'
                },
                dragsort: {
                    name: 'dragsort',
                    icon: 'fa fa-arrows',
                    title: __('Drag to sort'),
                    extend: 'data-toggle="tooltip"',
                    classname: 'btn btn-xs btn-primary btn-dragsort'
                }
            };

            var table = $("#table");
            $(document).on("click", "#resetFromSearch", function () {
                $(".form-commonsearch [type=reset]").trigger("click");
            });
            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                search: false,
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id'), operate: false},
                        {field: 'name', title: __('Name'), operate: 'LIKE'},
                        {field: 'media_type', title: __('Media_type'), searchList: {'image':__('Image'), 'video':__('Video')}, formatter: Table.api.formatter.normal},
                        {field: 'media', title: __('Media'), events: Controller.api.events.mediaEvent, formatter: Controller.api.formatter.formatMedia, operate: false},
                        {field: 'logo', title: __('Logo'), events: Table.api.events.image, formatter: Table.api.formatter.image, operate: false},
                        {field: 'qr_id', title: __('Qrcode'), formatter: Controller.api.formatter.formatQrcode, events: Controller.api.events.qrEvent, operate: false},
                        {field: 'version', title: __('Version'), searchList: {'base':__('BaseVersion'), 'pro':__('ProVersion'), 'full':__('FullVersion')}, formatter: Table.api.formatter.status},
                        {field: 'status', title: __('Status'), searchList: {"normal":__('Normal'),"hidden":__('Hidden')}, formatter: Table.api.formatter.status},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', autocomplete:false, formatter: Table.api.formatter.datetime},
                        {
                            field: 'operate',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'result',
                                    text: __('Result'),
                                    title: __('Relation')+__('Result'),
                                    icon: 'fa fa-link',
                                    classname: 'btn btn-info btn-xs btn-dialog',
                                    extend: 'data-area=["80%","80%"]',//调整弹窗尺寸这里只能按这种格式写
                                    url: function(row){
                                        return Fast.api.fixurl('mbti/result/index?scene_id='+row.id);
                                    }
                                },
                                {
                                    name: 'evaluate_result',
                                    text: __('MbtiTest'),
                                    title: __('Relation')+__('MbtiTest'),
                                    icon: 'fa fa-link',
                                    classname: 'btn btn-danger btn-xs btn-dialog',
                                    extend: 'data-area=["80%","80%"]',//调整弹窗尺寸这里只能按这种格式写
                                    url: function(row){
                                        return Fast.api.fixurl('mbti/evaluate/index?scene_id='+row.id);
                                    }
                                },
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindAddEvent();
        },
        edit: function () {
            Controller.api.bindEditEvent();
        },
        api: {
            bindAddEvent: function () {
                $(document).on('click', "input[name='row[media_type]']", function () {
                    if($(this).val()){
                        $("input[name='row[media]']").val("");
                        $("#fachoose-media").data("mimetype", $(this).val()+"/*");
                        $("#faupload-media").data("mimetype", $(this).val()+"/*");
                    }
                });
                $("input[name='row[media_type]']:checked").trigger("click");
                Form.api.bindevent($("form[role=form]"));
            },
            bindEditEvent: function () {
                $(document).on('click', "input[name='row[media_type]']", function () {
                    if($(this).val()){
                        const preMediaType = $("#pre_media_type").html();
                        const preMedia = $("#pre_media").html();
                        $("#p-media .btn-trash").trigger("click");
                        $("input[name='row[media]']").val($(this).val() == preMediaType ? preMedia : "");
                        $("#fachoose-media").data("mimetype", $(this).val()+"/*");
                        $("#faupload-media").data("mimetype", $(this).val()+"/*");
                        if($(this).val() == preMediaType){
                            /**
                             * 初始化预览数据-需要参考require-form.js中
                             * Form.events.faselect方法中
                             * parent.Fast.api.open打开页面的options参数中
                             * callback内对是否多选（multiple）的处理方式
                             * 调整为自己业务逻辑匹配的代码，这里只是单选所以只有如下代码
                             */
                            $("#c-media").val(Fast.api.cdnurl(preMedia)).trigger("change").trigger("validate");
                            $("#fachoose-media").trigger("fa.event.selectedfile", {multiple: false, url: preMedia});
                        }
                    }
                });
                $("input[name='row[media_type]']:checked").trigger("click");
                Form.api.bindevent($("form[role=form]"));
            },
            events:{
                mediaEvent: {
                    'click .media-center': function (e, value, row, index) {
                        if(row.media_type == 'image') {
                            var data = [];
                            value = value === null ? '' : value.toString();
                            var arr = value != '' ? value.split(",") : [];
                            var url;
                            $.each(arr, function (index, value) {
                                url = Fast.api.cdnurl(value);
                                data.push({
                                    src: url,
                                    thumb: url.match(/^(\/|data:image\\)/) ? url : url + Config.upload.thumbstyle
                                });
                            });
                            Layer.photos({
                                photos: {
                                    "start": $(this).parent().index(),
                                    "data": data
                                },
                                anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                            });
                        }else{
                            layer.open({
                                type: 1,
                                area: ['500px', '300px'], // 宽高
                                title: false, // 不显示标题栏
                                closeBtn: 1,
                                shadeClose: false, // 点击遮罩关闭层
                                content: '<div style="display: flex;align-items: center;justify-content: space-around;height: 100%;width: 100%;"><video controls autoplay style="width: 480px;height: 270px;" src="'+Fast.api.cdnurl(value)+'"></video></div>'

                            });
                        }
                    },
                },
                qrEvent: {
                    'click .qr-center': function (e, value, row, index) {
                        var data = [];
                        value = row.id.toString();
                        var arr = value != '' ? value.split(",") : [];
                        var url;
                        $.each(arr, function (index, value) {
                            url = Fast.api.fixurl('mbti/scene/scene_qr?id='+value);
                            data.push({
                                src: url,
                                thumb: url.match(/^(\/|data:image\\)/) ? url : url + Config.upload.thumbstyle
                            });
                        });
                        Layer.photos({
                            photos: {
                                "start": $(this).parent().index(),
                                "data": data
                            },
                            anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                        });
                    },
                }
            },
            formatter: {
                image: function (value, row, index) {
                    return Table.api.formatter.images.call(this, value, row, index);
                },
                formatMedia: function (value, row, index) {
                    var classname = 'img-sm media-center';
                    if(row.media_type == 'image'){
                        value = value == null || value.length === 0 ? '' : value.toString();
                        var arr = value !== '' ? (value.indexOf('data:image/') === -1 ? value.split(',') : [value]) : [];
                        var html = [];
                        var url;
                        $.each(arr, function (i, value) {
                            value = value ? value : '/assets/img/blank.gif';
                            url = Fast.api.cdnurl(value, true);
                            //匹配本地、data:image、或已包含标识符首字符
                            url = !Config.upload.thumbstyle || url.match(/^(\/|data:image\/)/) || url.indexOf(Config.upload.thumbstyle.substring(0, 1)) > -1 ? url : url + Config.upload.thumbstyle;
                            html.push('<a href="javascript:"><img class="' + classname + '" src="' + url + '" /></a>');
                        });
                        return html.join(' ');
                    } else {
                        var html = '';
                        const extArr = row.media.split(".");
                        html = '<a href="javascript:" ><img class="' + classname + '" src="' + Fast.api.fixurl("ajax/icon") + "?suffix=" + extArr[(extArr.length-1)] + '"></a>';
                        return html;
                    }
                },
                formatQrcode: function (value, row, index) {
                    var classname = 'img-sm qr-center';
                    value = row.id.toString();
                    var arr = value !== '' ? (value.indexOf('data:image/') === -1 ? value.split(',') : [value]) : [];
                    var html = [];
                    var url;
                    $.each(arr, function (i, value) {
                        value = value ? value : '/assets/img/blank.gif';
                        url = Fast.api.fixurl('mbti/scene/scene_qr?id='+value);
                        //匹配本地、data:image、或已包含标识符首字符
                        url = !Config.upload.thumbstyle || url.match(/^(\/|data:image\/)/) || url.indexOf(Config.upload.thumbstyle.substring(0, 1)) > -1 ? url : url + Config.upload.thumbstyle;
                        html.push('<a href="javascript:"><img class="' + classname + '" src="' + url + '" /></a>');
                    });
                    return html.join(' ');
                }
            }
        }
    };
    return Controller;
});
